package com.example.service.flowable.impl;

import com.example.service.flowable.FlowableServiceAbstract;
import com.example.service.flowable.IGeneralFlowableService;
import com.example.vo.ResultVo;
import com.example.vo.process.resp.MyStart;
import com.example.vo.process.resp.MyTask;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用流程实例服务实现类
 *
 * @author wsl
 */
@Service
public class GeneralFlowableIServicempl extends FlowableServiceAbstract implements IGeneralFlowableService {

    @Override
    public ResultVo getMyTasks(String userId) {
        //1、查询用户代理所有任务，按任务开始时间倒序排列
        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId)
                .orderByTaskCreateTime()
                .desc()
                .list();
        List<MyTask> myTasks = new ArrayList<>();
        list.forEach(e->{
            MyTask myTask = new MyTask();
            //2、查询流程定义实例
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(e.getProcessDefinitionId())
                    .singleResult();

            myTask.setCreateTime(e.getCreateTime())
                    .setIsEnd(e.getEndTime()!=null)
                    .setTaskId(e.getId())
                    .setTaskName(e.getName())
                    .setProcessInstanceId(e.getProcessInstanceId())
                    .setProcessDefinitionName(processDefinition.getName())
                    .setDurationMillisecond(e.getDurationInMillis());
            myTasks.add(myTask);
        });
        return ResultVo.response(myTasks);
    }

    @Override
    public ResultVo getMyStart(String userId) {
        //1、查询我发起的所有流程，按照发起时间倒序排列
        List<HistoricProcessInstance> list = historyService
                .createHistoricProcessInstanceQuery()
                .startedBy(userId)
                .orderByProcessInstanceStartTime()
                .desc()
                .list();
        List<MyStart> myStarts = new ArrayList<>();
        list.forEach(e->{
            MyStart myStart = new MyStart();
            myStart.setEndTime(e.getEndTime())
                    .setIsEnd(e.getEndTime()!=null)
                    .setProcessDefinitionName(e.getProcessDefinitionName())
                    .setStartTime(e.getStartTime())
                    .setProcessInstanceId(e.getId())
                    .setDurationTime(e.getDurationInMillis());
            myStarts.add(myStart);
        });
        return ResultVo.response(myStarts);
    }


}
